package com.example.day44.widget;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.example.day44.R;
import com.example.day44.wm.WmHelper;

/**
 * @author zhangwei
 * @version V1.icon
 * @Title: Advanced
 * @Package com.example.day44.widget
 * @Description:
 * @date 15/10/28 上午11:19
 *
 *
 *
 *
 *
 * update
 */

public class FloatView extends ImageView {
    private WindowManager windowManager;
    private WindowManager.LayoutParams params;
    private int statusHeight;


    public FloatView(Context context) {
        super(context);
        init();

    }

    private void init() {
        statusHeight = getStatusHeight(getContext());
        setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT)
        );
        setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon));
        windowManager = WmHelper.getInstance().getWm();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int width = getWidth();
        int heigth = getHeight();
        int x =0;
        int y =0;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = (int) event.getX();
                y = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:

                params.x = (int) event.getRawX() - x;
                //相对控件的
                params.y = ((int) event.getRawY() - statusHeight) - y;
                windowManager.updateViewLayout(this, params);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }


        return super.onTouchEvent(event);
    }


    public void setParams(WindowManager.LayoutParams params) {
        this.params = params;
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

}
